package com.lyc.dao.impl;

import com.lyc.dao.BaseAdminDao;
import com.lyc.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

public class BaseAdminDaoImpl implements BaseAdminDao {

    private static final String SQL_UPDATE_LOGIN_TIME = "update eadmin set logintime=?,loginip=? where username=?";
    private static final String SQL_LOGIN = "select id from eadmin where username=? and password=?";

    /**
     * 根据用户名，更新登录时间和登录ip
     * @param username
     * @param date
     * @param ip
     */
    @Override
    public void updateLoginTime(String username, Date date, String ip) {
        // 1.获取连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        // 2.预编译SQL语句
        try {
            state = conn.prepareStatement(SQL_UPDATE_LOGIN_TIME);
            // 3.填充参数
            state.setDate(1, new java.sql.Date(date.getTime()));
            state.setString(2, ip);
            state.setString(3, username);
            // 4.执行
            state.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            // 5.释放资源
            DruidUtil.close(conn, state, null);
        }
    }

    /**
     * 管理员根据账号密码登录
     * @param username
     * @param password
     * @return 登录的结果，true表示成功，false表示失败
     */
    @Override
    public boolean login(String username, String password) {
        // 1.获取连接
        Connection conn = DruidUtil.getConnection();
        PreparedStatement state = null;
        ResultSet resultSet = null;
        // 2.预编译SQL语句
        try {
            state = conn.prepareStatement(SQL_LOGIN);
            // 3.填充参数
            state.setString(1, username);
            state.setString(2, password);
            // 4.执行
            resultSet = state.executeQuery();
            // 5.根据查询结果，返回结果集
            return resultSet.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            // 6.释放资源
            DruidUtil.close(conn, state, null);
        }
        return false;
    }
}
